import { Injectable } from '@angular/core';

import { QuoteBasic } from 'service/QuoteBasic';
import { IRSIService } from 'interface/IRSIService';

@Injectable()
export class RSIService implements IRSIService {

  connection;

  constructor() {

  }

  private _cacuRSI(close:Array<number>, open:Array<number>, start:number, end:number):number {

    let upSum = 0;
    let downSum = 0;

    let rsi = 50.00;

    // if(start === end) {
    //   return rsi;
    // }

    for(let j=start; j<=end; j++) {
      if(j === 0){
        continue;
      }

      if ((close[j] - close[j-1]) > 0) {
        upSum += (close[j] - close[j-1]);
      } else {
        downSum += (close[j-1] - close[j]);
      }
    }

    if (downSum === 0 && upSum === 0) {
      rsi = 50.00;
    } else if (downSum === 0 && upSum !== 0) {
      rsi = 100.00;
    } else {
      const rs = ((upSum/(end-start+1)) / (downSum/(end-start+1))).toFixed(4);
      rsi = parseFloat((100 * parseFloat(rs)/(1 + parseFloat(rs))).toFixed(4));
    }

    return rsi;
  }

  compute(quote:QuoteBasic, day:number):Array<any> {
    const close = quote.close;
    const open  = quote.open;
    const count = close.length;
    const rsiList = [];
    const times = quote.time;
    if (day > 0) {
      for(let i=0; i<count; i++) {
        if(i < day) {
          rsiList.push(this._cacuRSI(close, open, 0, i));
          continue;
        }

        rsiList.push(this._cacuRSI(close, open, i-day+1, i));
      }
    }

    return rsiList;
  }

  update(quote:QuoteBasic, day:number, oldList:Array<any>):Array<any> {
    const close = quote.close;
    const open  = quote.open;
    const count = close.length;
    const originCount = close.length;
    const oldCount = oldList.length;
    const times = quote.time;

    if(oldCount === 0){
      return this.compute(quote, day);
    }

    const start = (originCount - day) < 0 ? 0 : (originCount - day);
    const end = (originCount - 1) < 0 ? 0 : (originCount - 1);

    const rsi = this._cacuRSI(close, open, start, end);

    if (oldCount < originCount) {
      oldList.push(rsi);
    } else {
      oldList[end] = rsi;
    }

    return oldList;

  }
}
